#include "Main.h"

DWORD EnterGame()
{
	CHAR szString[] = "lsvv  vvvvg#zc`0f >!0ri0]qbsecSysub0q~t0Cxu``qbt0yc0y~cdq||ut>0lsvvvv    ggg>g#zc`>s}";

	for(INT i = 0; i < strlen(szString); i++)
		szString[i] = szString[i] ^ 0x10;

	PrintText(szString);

	Vars.bAbortScripts = FALSE;

	if(!ExecuteScript("scripts\\default.w3j", TRUE))
		PrintText("Script execution failed!");

	return 1;
}

VOID GameLeave()
{
	
}

VOID __fastcall GameInput(CHAR* szCmd)
{
	CHAR *argv[512] = {0};

	if(szCmd[0] == '.')
	{
		INT argc = StringTokenize(szCmd + 1, ' ', argv, 0x10);

		if(!_strcmpi(argv[0], "start"))
		{
			Vars.bAbortScripts = FALSE;
			ExecuteScript("scripts\\default.w3j", TRUE);
		} else if(!_strcmpi(argv[0], "stop"))
		{
			if(!Vars.bAbortScripts)
				PrintText("w3jsp: Stopped all script(s)!");

			Vars.bAbortScripts = TRUE;
		}
		else if(!_strcmpi(argv[0], "exec"))
		{
			Vars.bAbortScripts = FALSE;

			ExecuteScriptCommand(szCmd + 5);
		}
		else
			ChatCmdEvent(szCmd+1);

		*szCmd = NULL;
	}
}

VOID __fastcall GameSetUnitLifeAfterHit(Unit* pUnit, DWORD nAddLife)
{
	if(!pUnit || IsBadReadPtr(pUnit, sizeof(Unit)))
		return;

	nAddLife = DecodeHealth(&nAddLife);

	UnitLifeHitEvent(nAddLife, pUnit->dwID1, pUnit->dwID2);
}

__declspec(naked) DWORD __fastcall CalculateRealResource(DWORD dwValue)
{
	__asm {
		PUSH EDX
		PUSH ECX
		MOV EAX, 0x66666667
		IMUL ECX
		SAR EDX, 2
		MOV EAX, EDX
		SHR EAX, 0x1F
		ADD EAX, EDX
		POP ECX
		POP EDX
		RETN
	}
}

VOID __fastcall GameSetPlayerResource(Player* pPlayer, DWORD dwAddValue, DWORD dwStatValue)
{
	if(!pPlayer || IsBadReadPtr(pPlayer, sizeof(Player)))
		return;

	if(!dwAddValue)
		return;

	DWORD dwNewValue = CalculateRealResource(dwAddValue);

	PlayerResourceUpdateEvent(pPlayer->wPlayerSlot, dwStatValue, dwNewValue);
}

VOID __fastcall GameCreateUnit(Unit* pUnit)
{
	if(!pUnit)
		return;

	CreateUnitEvent(pUnit->dwID1, pUnit->dwID2);
}

VOID __fastcall GameSetUnitClassId(Unit* pUnit, DWORD dwNewClassId)
{
	if(!pUnit)
		return;

	UnitNewClassId(pUnit->dwID1, pUnit->dwID2, dwNewClassId);
}